package com.jemmyee.pizza.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.dao.Page;
import com.jemmyee.core.utils.EncryptUtils;
import com.jemmyee.pizza.entity.Address;
import com.jemmyee.pizza.entity.Card;
import com.jemmyee.pizza.entity.LogSys;
import com.jemmyee.pizza.entity.Person;
import com.jemmyee.pizza.entity.User;
import com.jemmyee.pizza.service.IAddressService;
import com.jemmyee.pizza.service.ICardService;
import com.jemmyee.pizza.service.ILogSysService;
import com.jemmyee.pizza.service.IPersonService;
import com.jemmyee.pizza.web.Constants;
import com.jemmyee.pizza.web.bean.LogBean;
import com.jemmyee.pizza.web.bean.PersonBean;

/**
 * @author qiuchao 2010-12-17
 */
@Controller
@RequestMapping("/admin/person")
public class PersonController {
	private static Log log = LogFactory.getLog(PersonController.class);
	@Autowired
	private IPersonService<Person> personService;
	@Autowired
	private ICardService<Card> cardService;
	@Autowired
	private IAddressService<Address> addressService;
	@Autowired
	private ILogSysService<LogSys> logSysService;
/**
 * 添加客户数据初始化
 * @return
 */
	@RequestMapping("/to_add")
	public ModelAndView toAdd() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/admin/person/add");
		return mv;
	}
/**
 * 执行客户添加动作
 * @param person
 * @param request
 * @return
 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> add(@RequestBody Person person,	HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<Person> lt = personService.findByProperty("personNumber", person.getPersonNumber());
		if(lt != null && lt.size() > 0){
			model.put("msg","error");
		}else{
			person.setCreateTime(new Date());
			personService.save(person);
			model.put("msg","succ");
		}
		
//		mv.setViewName("/person/view");
//		mv.addObject("person", person);
		return model;
	}
/**
 * 客户列表
 * @param startIndex
 * @param from
 * @param bean
 * @param request
 * @return
 */
	@RequestMapping("/list/{from}/{startIndex}")
	public ModelAndView list(@PathVariable Integer startIndex,@PathVariable String from,@ModelAttribute PersonBean bean,HttpServletRequest request) {
		DetachedCriteria dc = DetachedCriteria.forClass(Person.class);
		PersonBean personBean = new PersonBean();
		if (from.equals("form")) {
			personBean = bean;
			request.getSession().setAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN, personBean);
		}
		if (from.equals("page")) {
			if (request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN) != null) {
				personBean = (PersonBean) request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
			}
		}
		if (from.equals("menu")) {
			System.out.println("menu is call");
		}

		if(personBean.getName() != null){
			dc.add(Restrictions.like("personName", personBean.getName(), MatchMode.ANYWHERE));
		}
		
		if(personBean.getNumber() != null){
			dc.add(Restrictions.like("personNumber", personBean.getNumber(), MatchMode.ANYWHERE));
		}
		
		if(personBean.getType() != null){
			dc.add(Restrictions.eq("personType", personBean.getType()));
		}
		// 发布时间
		if (personBean.getStartTime() != null) {
			dc.add(Restrictions.ge("createTime", personBean.getStartTime()));
		}
		if (personBean.getEndTime() != null) {
			dc.add(Restrictions.le("createTime", personBean.getEndTime()));
		}

//		dc.addOrder(Order.desc("createTime"));
		ModelAndView mv = new ModelAndView();
		Page page = personService.findPageByCriteria(dc,Constants.DEFAULT_PAGESIZE, startIndex,"createTime");
		mv.addObject("page", page);
		mv.addObject("personBean", personBean);
		mv.setViewName("/admin/person/list");
		return mv;
	}
/**
 * 客户修改数据初始化	
 * @param id
 * @return
 */
	@RequestMapping("/to_edit/{id}")
	public ModelAndView toEdit(@PathVariable Integer id){
	   ModelAndView mv=new ModelAndView();
	   Person person=personService.findById(id);
	   mv.setViewName("/admin/person/edit");
	   mv.addObject("person",person);
	   return mv;
	}
	
/**
 * 执行客户修改动作
 * @param person
 * @param request
 * @return
 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> edit(@RequestBody Person person,HttpServletRequest request)
	{   
		Map<String, Object> model = new HashMap<String, Object>();
		Person p = personService.findById(person.getPersonId());
//		User temp=userService.findAll().get(0);
		if(p == null){
			model.put("msg","error");
		}else{
			p.setPersonName(person.getPersonName());
			p.setPassWord(person.getPassWord());
			p.setPersonIdentity(person.getPersonIdentity());
			p.setPersonPhone(person.getPersonPhone());
			p.setPersonMobile(person.getPersonMobile());
			personService.update(p);
			model.put("msg","succ");
		}
		return model;
	}
/**
 * 删除用户
 * @param request
 * @return
 */
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public Map<String, Object> delete(@PathVariable Integer id) {
		Map<String, Object> model = new HashMap<String, Object>();
		Person p = personService.findById(id);
		if(p != null){
			personService.delete(p);
			/* 同时删除此用户的卡    */
			List<Card> cardList = cardService.findByProperty("personId", id);
			if(cardList != null && cardList.size() > 0){
				cardService.deleteAll(cardList);
			}
			/* 同时删除此用户的地址    */
			List<Address> addressList = addressService.findByProperty("personId", id);
			if(addressList != null && addressList.size() > 0){
				addressService.deleteAll(addressList);
			}
			
			model.put("msg","succ");
		}else{
			model.put("msg","error");
		}
		return model;
	}
	
	
/**
 * 卡列表
 * @param id
 * @return
 */
	@RequestMapping("/card_list/{id}")
	public ModelAndView cardList(@PathVariable Integer id) {
		ModelAndView mv=new ModelAndView();
		List<Card> cardList = cardService.findByProperty("personId", id);
		Person person = personService.findById(id);
		mv.setViewName("/admin/person/card_list");
		mv.addObject("list",cardList);
		mv.addObject("person",person);
		return mv;
	}
/**
 * 地址列表
 * @param id
 * @return
 */
	@RequestMapping("/address_list/{id}")
	public ModelAndView addressList(@PathVariable Integer id) {
		ModelAndView mv=new ModelAndView();
		List<Address> addressList = addressService.findByProperty("personId", id);
		Person person = personService.findById(id);
		mv.setViewName("/admin/person/address_list");
		mv.addObject("list",addressList);
		mv.addObject("person",person);
		return mv;
	}
/**
 * 添加卡	
 * @param card
 * @param request
 * @return
 */
	@RequestMapping("/add_card")
	@ResponseBody
	public Map<String, Object> cardAdd(@RequestBody Card card,	HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		card.setCreateTime(new Date());
		cardService.save(card);
		model.put("msg","succ");
		return model;
	}
/**
 * 添加地址	
 * @param address
 * @param request
 * @return
 */
	@RequestMapping("/add_address")
	@ResponseBody
	public Map<String, Object> addressAdd(@RequestBody Address address,	HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		address.setCreateTime(new Date());
		addressService.save(address);
		model.put("msg","succ");
		return model;
	}
/**
 * 删除卡	
 * @param request
 * @return
 */
	@RequestMapping("/delete_card/{id}")
	@ResponseBody
	public Map<String, Object> cardDelete(@PathVariable Integer id) {
		Map<String, Object> model = new HashMap<String, Object>();
		Card c = cardService.findById(id);
		if(c != null){
			cardService.delete(c);
			model.put("msg","succ");
		}else{
			model.put("msg","error");
		}
		return model;
	}
/**
 * 删除地址	
 * @param request
 * @return
 */
	@RequestMapping("/delete_address/{id}")
	@ResponseBody
	public Map<String, Object> addressDelete(@PathVariable Integer id) {
		Map<String, Object> model = new HashMap<String, Object>();
		Address a = addressService.findById(id);
		if(a != null){
			addressService.delete(a);
			model.put("msg","succ");
		}else{
			model.put("msg","error");
		}
		return model;
	}
/**
 * 充值数据初始化	
 * @param id
 * @return
 */
	@RequestMapping("/to_recharge_card/{id}")
	public ModelAndView toRechargeCard(@PathVariable Integer id){
	   ModelAndView mv=new ModelAndView();
	   Card card=cardService.findById(id);
	   Person person = new Person();
	   if(card != null && card.getPersonId() != null){
		   person = personService.findById(card.getPersonId());
	   }
	   mv.setViewName("/admin/person/recharge_card");
	   mv.addObject("card",card);
	   mv.addObject("person",person);
	   return mv;
	}
/**
 * 执行充值动作	
 * @param card
 * @param request
 * @return
 */
	@RequestMapping("/recharge_card")
	@ResponseBody
	public Map<String, Object> rechargeCard(@RequestBody Card card,	HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		if(card != null && card.getCardId() != null){
			Card c = cardService.findById(card.getCardId());
			if(c != null){
				c.setMoney((c.getMoney()==null?0:c.getMoney())+card.getMoney());
				cardService.update(c);
				
				Person person = personService.findById(c.getPersonId());
				String s = null;
				if(person.getPersonType() == 0)
					s = "零散户";
				else if(person.getPersonType() == 1)
					s = "商业户";
				else if(person.getPersonType() == 2)
					s = "集体户";
				LogSys lg = new LogSys();
				lg.setType(111);
				lg.setLtime(new Date());
				lg.setLdesc("用户类型"+s+"，用户："+person.getPersonName()+"，卡号："+c.getCardNumber()+"，充值："+card.getMoney()+"，余额"+c.getMoney());
				logSysService.save(lg);
				model.put("msg","succ");
			}else{
				model.put("msg","error");
			}
		}else{
			model.put("msg","error");
		}
		return model;
	}
/**
 * 提现数据初始化
 * @param id
 * @return
 */
	@RequestMapping("/to_withdraw_card/{id}")
	public ModelAndView toWithdrawCard(@PathVariable Integer id){
	   ModelAndView mv=new ModelAndView();
	   Card card=cardService.findById(id);
	   Person person = new Person();
	   if(card != null && card.getPersonId() != null){
		   person = personService.findById(card.getPersonId());
	   }
	   mv.setViewName("/admin/person/withdraw_card");
	   mv.addObject("card",card);
	   mv.addObject("person",person);
	   return mv;
	}
/**
 * 执行提现动作	
 * @param card
 * @param request
 * @return
 */
	@RequestMapping("/withdraw_card")
	@ResponseBody
	public Map<String, Object> withdrawCard(@RequestBody Card card,	HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		if(card != null && card.getCardId() != null){
			Card c = cardService.findById(card.getCardId());
			if(c != null && (c.getMoney()>=card.getMoney())){
				c.setMoney(c.getMoney()-card.getMoney());
				cardService.update(c);
				
				Person person = personService.findById(c.getPersonId());
				String s = null;
				if(person.getPersonType() == 0)
					s = "零散户";
				else if(person.getPersonType() == 1)
					s = "商业户";
				else if(person.getPersonType() == 2)
					s = "集体户";
				LogSys lg = new LogSys();
				lg.setType(222);
				lg.setLtime(new Date());
				lg.setLdesc("用户类型"+s+"，用户："+person.getPersonName()+"，卡号："+c.getCardNumber()+"，提现："+card.getMoney()+"，余额"+c.getMoney());
				logSysService.save(lg);
				model.put("msg","succ");
			}else{
				model.put("msg","error");
			}
		}else{
			model.put("msg","error");
		}
		return model;
	}
/**
 * 转账数据初始化
 * @param id
 * @return
 */
	@RequestMapping("/to_transfer_card/{id}")
	public ModelAndView toTransferCard(@PathVariable Integer id){
	   ModelAndView mv=new ModelAndView();
	   Card card=cardService.findById(id);
	   Person person = new Person();
	   if(card != null && card.getPersonId() != null){
		   person = personService.findById(card.getPersonId());
	   }
	   mv.setViewName("/admin/person/transfer_card");
	   mv.addObject("card",card);
	   mv.addObject("person",person);
	   return mv;
	}
	
	
	@RequestMapping("/transfer_card_list")
	public ModelAndView transferCardList(@ModelAttribute PersonBean bean){
	   ModelAndView mv=new ModelAndView();
	   Person person = personService.findById(bean.getPersonId());
	   Card card=cardService.findById(bean.getCardId());

	   DetachedCriteria dc = DetachedCriteria.forClass(Person.class);
	   if(bean.getName() != null){
			dc.add(Restrictions.like("personName", bean.getName(), MatchMode.ANYWHERE));
		}
		
		if(bean.getNumber() != null){
			dc.add(Restrictions.like("personNumber",bean.getNumber(), MatchMode.ANYWHERE));
		}   
	   List<Person> list = personService.findByCriteria(dc);
	   mv.setViewName("/admin/person/transfer_card");
	   mv.addObject("card",card);
	   mv.addObject("person",person);
	   mv.addObject("list",list);
	   return mv;
	}
	
	@RequestMapping("/get_card_list/{id}")
	@ResponseBody
	public Map<String, Object> getCardList(@PathVariable String id) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<Card> cardList = cardService.findByProperty("personId", Integer.parseInt(id));
		model.put("msg","succ");
		model.put("id",id);
		StringBuffer sb = new StringBuffer();
		sb.append("<table border=\"0\" cellpadding=\"\" cellspacing=\"1\" align=\"center\" width=\"92%\" id=\"web_tab\">");
		sb.append("<tr>");
		sb.append("<td width=\"40%\">卡号</td>");
		sb.append("<td width=\"20%\">余额</td>");
		sb.append("<td width=\"20%\">操作</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		if(cardList != null && cardList.size() > 0){
			for(Card card : cardList){
				sb.append("<td>"+card.getCardNumber()+"</td>");
				sb.append("<td>"+(card.getMoney()==null?0:card.getMoney())+"</td>");
				sb.append("<td><input type=\"button\" class=\"but\" value=\"选择\" onclick=\"set_card_number('"+id+"','"+card.getCardId()+"','"+card.getCardNumber()+"')\"/></td>");
				sb.append("</tr>");
				sb.append("<tr>");
			}
		}else{
			sb.append("<td colspan=\"3\" align=\"center\">此用户尚未添加卡信息</td>");
			sb.append("</tr>");
			sb.append("<tr>");
		}
		sb.append("<td colspan=\"3\" align=\"center\"><input type=\"button\" class=\"but\" value=\"关闭\" onclick=\"hidePopup();\"></td>");
		sb.append("</tr>");
		sb.append("</table>");
		model.put("sb",sb);
		return model;
	}
/**
 * 执行转账动作	
 * @param card
 * @param request
 * @return
 */
	@RequestMapping("/transfer_card/{fromCardId}/{toCardId}/{money}")
	@ResponseBody
	public Map<String, Object> transferCard(@PathVariable Integer fromCardId,@PathVariable Integer toCardId,@PathVariable Double money) {
		Map<String, Object> model = new HashMap<String, Object>();
		Card fromCard = cardService.findById(fromCardId);
		Card toCard = cardService.findById(toCardId);
		if(fromCard != null && toCard != null){
			if(fromCard.getMoney() < money){
				model.put("msg","error");
			}else{
				toCard.setMoney((toCard.getMoney()==null?0:toCard.getMoney()) + money);
				cardService.update(toCard);
				fromCard.setMoney(fromCard.getMoney() - money);
				cardService.update(fromCard);
				LogSys lg = new LogSys();
				lg.setType(333);
				lg.setLtime(new Date());
				lg.setLdesc("客户转账，转出账号："+fromCard.getCardNumber()+"，转出账号余额"+fromCard.getMoney()+"，转入账号："+toCard.getCardNumber()+"，转入账号余额："+toCard.getMoney());
				logSysService.save(lg);
				model.put("msg","succ");
			}
		}else{
			model.put("msg","error");
		}
		return model;
	}
}
